package com.stylefeng.guns.modular.wz.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.plugins.pagination.PageHelper;
import com.stylefeng.guns.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.common.persistence.model.PfFile;
import com.stylefeng.guns.common.persistence.model.WzAnswer;
import com.stylefeng.guns.common.persistence.model.WzQuestion;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.modular.wz.dao.WzAnswerDao;
import com.stylefeng.guns.modular.wz.dao.WzQuestionDao;
import com.stylefeng.guns.modular.wz.service.IPfFileService;
import com.stylefeng.guns.modular.wz.service.IWzAnswerService;
import com.stylefeng.guns.modular.wz.service.IWzQuestionService;
import com.stylefeng.guns.modular.wz.warpper.WzQuestionWarpper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 问题控制器
 *
 * @author fengshuonan
 * @Date 2018-03-16 10:03:58
 */
@Controller
@RequestMapping("/wzQuestion")
public class WzQuestionController extends BaseController {

    private String PREFIX = "/wz/wzQuestion/";

    @Autowired
    private IWzQuestionService wzQuestionService;
    @Autowired
    private IWzAnswerService wzAnswerService;
    @Autowired
    private IPfFileService pfFileService;
    @Autowired
    private WzQuestionDao wzQuestionDao;

    @Autowired
    private WzAnswerDao wzAnswerDao;

    /**
     * 跳转到问题首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "wzQuestion.html";
    }

    /**
     * 跳转到添加问题
     */
    @RequestMapping("/wzQuestion_add")
    public String wzQuestionAdd() {
        return PREFIX + "wzQuestion_add.html";
    }

    /**
     * 跳转到修改问题
     */
    @RequestMapping("/wzQuestion_update/{wzQuestionId}")
    public String wzQuestionUpdate(@PathVariable Long wzQuestionId, Model model) throws IOException {
        WzQuestion wzQuestion = wzQuestionService.selectById(wzQuestionId);
        model.addAttribute("questionTypeTemp", wzQuestion.getType());
        model.addAttribute("item", wzQuestion);
        model.addAttribute("type", ConstantFactory.me().getDictsByName("问题类型", wzQuestion.getType()));
        model.addAttribute("questionType", ConstantFactory.me().getDictsByName("问题形式", wzQuestion.getQuestionType()));
        LogObjectHolder.me().set(wzQuestion);
        if (2 == wzQuestion.getType()) {
            Map<String, Object> map = new HashMap<>();
            map.put("question_id", wzQuestionId);
            List<WzAnswer> answerList = wzAnswerService.selectByMap(map);
            if (2 == wzQuestion.getQuestionType()) {
                for (WzAnswer answer : answerList) {
                    PfFile pfFile = pfFileService.selectOne(new EntityWrapper<PfFile>().eq("file_url",answer.getAnswerPic()));
                    answer.setAnswerPic(pfFile.getFileId().toString());
                }
            }
            model.addAttribute("answerList", answerList);

        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("question_id", wzQuestionId);
            List<WzAnswer> answerList_1 = wzAnswerService.selectByMap(map);
            if (2 == wzQuestion.getQuestionType()) {
                for (WzAnswer answer : answerList_1) {
                    PfFile pfFile = pfFileService.selectOne(new EntityWrapper<PfFile>().eq("file_url",answer.getAnswerPic()));
                    answer.setAnswerPic(pfFile.getFileId().toString());
                }
            }
            model.addAttribute("answerList_1", answerList_1);
        }
        return PREFIX + "wzQuestion_edit.html";
    }

    /**
     * 获取问题列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(required = false) String condition, Integer type, Integer status) {
        List<Map<String, Object>> wzQuestionList = wzQuestionDao.selectWzQuestions(null, condition,type,status);
        return new WzQuestionWarpper(wzQuestionList).warp();
    }

    /**
     * 新增问题
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(WzQuestion wzQuestion, WzAnswer wzAnswer, Integer questionType, String picIds) {
        Integer userId = ShiroKit.getUser().getId();
        wzQuestion.setModifierId(userId);
        wzQuestion.setPublishingType(1);
        wzQuestion.setCreateTime(new Date());
        wzQuestionService.insert(wzQuestion);
        wzAnswer.setQuestionId(wzQuestion.getQuestionId());
        if (2 == wzQuestion.getType()) {
            String answer = wzAnswer.getAnswer();
            String correctAnswer = answer.substring(answer.length() - 2, answer.length() - 1);//正确答案
            String[] answerArray = wzAnswer.getAnswer().split(";");//所有答案内容
            for (int i = 0; i < answerArray.length - 1; i++) {
                wzAnswer.setAnswer(answerArray[i].substring(2));
                if (correctAnswer.equals(answerArray[i].substring(0, 1))) {
                    wzAnswer.setIsTrue(1);
                } else {
                    wzAnswer.setIsTrue(0);
                }
                if (questionType == 2) {
                    if (StringUtils.isNotBlank(picIds)) {
                        String[] picArray = picIds.split(";");//所有答案图片
                        PfFile pfFile = pfFileService.selectById(Long.parseLong(picArray[i]));
                        if (pfFile == null) {
                            return super.SUCCESS_TIP.fail("id:" + picArray[i] + " 无效!");
                        } else {
                            wzAnswer.setAnswerPic(pfFile.getFileUrl());
                        }
                    }
                }
                wzAnswerService.insert(wzAnswer);
            }
        } else {
            String[] answerArray = wzAnswer.getAnswer().split(";");//所有答案内容
            for (int i = 0; i < answerArray.length; i++) {
                wzAnswer.setAnswer(answerArray[i].substring(2));
                if (questionType == 2) {
                    if (StringUtils.isNotBlank(picIds)) {
                        String[] picArray = picIds.split(";");//所有答案图片
                        PfFile pfFile = pfFileService.selectById(Long.parseLong(picArray[i]));
                        if (pfFile == null) {
                            return super.SUCCESS_TIP.fail("id:" + picArray[i] + " 无效!");
                        } else {
                            wzAnswer.setAnswerPic(pfFile.getFileUrl());
                        }
                    }
                }
                wzAnswerService.insert(wzAnswer);
            }
        }
        return super.SUCCESS_TIP;
    }

    /**
     * 检查问题是否存在
     */
    @RequestMapping(value = "/check")
    @ResponseBody
    public String check(WzQuestion wzQuestion) {
        String question = wzQuestion.getQuestion().trim();

        return "";
    }

    /**
     * 删除问题
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Long wzQuestionId) {
        WzQuestion question = wzQuestionService.selectById(wzQuestionId);
        if (question.getStatus() == 1) {
            wzQuestionService.deleteById(wzQuestionId);
            wzAnswerDao.deleteAnswerByQuestionID(wzQuestionId);
            return SUCCESS_TIP;
        } else {
            return SUCCESS_TIP.fail("只有待使用问题才可删除!");
        }
    }

    /**
     * 修改问题
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(WzQuestion wzQuestion, WzAnswer wzAnswer, String answerIds,String picIds) {
        wzQuestion.setUpdateTime(new Date());
        wzQuestionService.updateById(wzQuestion);
        String answer = wzAnswer.getAnswer();
        String correctAnswer = answer.substring(answer.length() - 2, answer.length() - 1);//正确答案
        String[] answerArray = wzAnswer.getAnswer().split(";");//所有答案内容
        String[] answerId = answerIds.split(";");
        for (int i = answerId.length; i < answerArray.length - 1; i++) {
            wzAnswer.setAnswer(answerArray[i].substring(2));
            if (correctAnswer.equals(answerArray[i].substring(0, 1))) {
                wzAnswer.setIsTrue(1);
            } else {
                wzAnswer.setIsTrue(0);
            }
            if (2==wzQuestion.getQuestionType()) {
                if (StringUtils.isNotBlank(picIds)) {
                    String[] picArray = picIds.split(";");//所有答案图片
                    PfFile pfFile = pfFileService.selectById(Long.parseLong(picArray[i]));
                    if (pfFile == null) {
                        return super.SUCCESS_TIP.fail("id:" + picArray[i] + " 无效!");
                    } else {
                        wzAnswer.setAnswerPic(pfFile.getFileUrl());
                    }
                }
            }
            wzAnswerService.insert(wzAnswer);
        }
        for (int i = 0; i < answerId.length; i++) {
            wzAnswer.setAnswer(answerArray[i].substring(2));
            wzAnswer.setAnswerId(Long.valueOf(answerId[i]));
            if (correctAnswer.equals(answerArray[i].substring(0, 1))) {
                wzAnswer.setIsTrue(1);
            } else {
                wzAnswer.setIsTrue(0);
            }
            if (2==wzQuestion.getQuestionType()) {
                if (StringUtils.isNotBlank(picIds)) {
                    String[] picArray = picIds.split(";");//所有答案图片
                    PfFile pfFile = pfFileService.selectById(Long.parseLong(picArray[i]));
                    if (pfFile == null) {
                        return super.SUCCESS_TIP.fail("id:" + picArray[i] + " 无效!");
                    } else {
                        wzAnswer.setAnswerPic(pfFile.getFileUrl());
                    }
                }
            }
            wzAnswerService.updateById(wzAnswer);
        }
        return super.SUCCESS_TIP;
    }


    /**
     * 问题详情
     */
    @RequestMapping(value = "/detail/{wzQuestionId}")
    @ResponseBody
    public Object detail(@PathVariable("wzQuestionId") Long wzQuestionId) {
        return wzQuestionService.selectById(wzQuestionId);
    }

    /**
     * 删除答案
     */
    @RequestMapping(value = "/deleteAnswer")
    @ResponseBody
    public Object deleteAnswer(WzQuestion wzQuestion, Long answerId) {
        Map<String, Object> map = new HashMap<>();
        map.put("answer_id", answerId);
        map.put("question_id", wzQuestion.getQuestionId());
        wzAnswerService.deleteByMap(map);
        return super.SUCCESS_TIP;
    }
}
